<template>
  <ele-page>
    <!-- 搜索表单 -->
    <search @search="reload" :job-id="jobId" ref="searchRef" />
    <ele-card :body-style="{ paddingTop: '8px' }">
      <!-- 表格 -->
      <ele-pro-table
        ref="tableRef"
        :columns="columns"
        :datasource="datasource"
        :show-overflow-tooltip="true"
        highlight-current-row
        row-key="id"
        v-model:selections="selections"
        row-click-checked
        stripe
        border
        :pagination="false"
      >
        <template #toolbar>
          <span style="font-weight: bold">
            {{ job.title }} - {{ company.company_name }}
          </span>
        </template>
        <template #tools>
          <el-button
            type="primary"
            class="ele-btn-icon"
            :icon="Reading"
            @click="openSignIn()"
          >
            签到表
          </el-button>
          <el-button
            type=""
            class="ele-btn-icon"
            :icon="DocumentCopy"
            @click="exportExcel()"
          >
            导出表格
          </el-button>
        </template>

        <template #sort="{ row }">
          <el-input v-model="row.sort" />
        </template>

        <template #status="{ row }">
          <el-tag :type="statusType(row.status)">
            {{ statusText(row.status) }}
          </el-tag>
        </template>

        <template #apply="{ row }">
          {{ row.apply_type }}
          <span v-if="row.dzyuba_id > 0" class="red">({{ row.dzyuba }})</span>
          <br />
          {{ row.apply_time }}
        </template>

        <template #cancel="{ row }">
          {{ row.cancel_type }}
          <br />
          {{ row.cancel_time }}
        </template>

        <template #contact="{ row }">
          <div v-if="row.contact == 1" class="pointer" @click="contact(row, 1)">
            {{ row.contact_user }}
            <br />
            {{ row.contact_time }}
          </div>
        </template>
        <template #remark="{ row }">
          <div
            v-for="v in row.note"
            :key="v.id"
            class="pointer"
            @click="editNote(v)"
          >
            {{ v.content }}
            <br />
          </div>
        </template>
        <template #action="{ row }">
          <el-link type="danger" :underline="false" @click="openCancel(row)">
            退定
          </el-link>
        </template>
      </ele-pro-table>
    </ele-card>
    <!-- 添加报名记录 -->
    <student v-model="showAdd" :job="job" @done="reload" @close="reload" />

    <!-- 发工资 -->
    <pay v-model="showPay" :job="job" @done="reload" @close="reload" />

    <!-- 处罚 -->
    <punish v-model="showPunish" :job="job" @done="reload" />

    <!-- 退定 -->
    <cancel v-model="showCancel" :data="current" @done="reload" />

    <!-- 签到表 -->
    <sign-in v-model="showSignIn" :job="job" @done="reload" />

    <!-- 备注 -->
    <note
      v-model="showNote"
      :data="current"
      :apply-record-id="currentId"
      @done="reload"
    />
  </ele-page>
</template>

<script setup>
  import { ref, unref, watch } from 'vue';
  import { Reading, DocumentCopy } from '@element-plus/icons-vue';
  import Search from './components/search.vue';
  import Pay from './components/pay.vue';
  import Punish from './components/punish.vue';
  import Student from './student/index.vue';
  import Cancel from './components/cancel.vue';
  import Note from './components/note.vue';
  import SignIn from './components/sign-in.vue';

  import {
    pageApplyRecord,
    setApplyRecordAccept,
    updateApplyRecoedSort,
    getJobById,
    exportApplyRecordList,
    updateApplyRecordContact,
    updateAirplane
  } from '@/api/company';
  import { useRouter } from 'vue-router';
  import { ElMessageBox } from 'element-plus/es';
  import { EleMessage } from 'ele-admin-plus/es';

  const { currentRoute } = useRouter();
  const ROUTE_PATH = '/company/apply';

  /** 表格实例 */
  const tableRef = ref(null);

  /** 表格实例 */
  const searchRef = ref(null);

  /** 表格列配置 */
  const columns = ref([
    {
      label: '状态',
      width: 70,
      slot: 'status'
    },

    {
      prop: 'realname',
      label: '名字',
      width: 75
    },
    {
      prop: 'tel',
      label: '电话',
      width: 112
    },
    {
      prop: 'gender',
      label: '性别',
      width: 60,
      align: 'center'
    },
    {
      prop: 'age',
      label: '年龄',
      width: 65,
      align: 'center'
    },
    {
      prop: 'paid',
      label: '已发',
      width: 75,
      align: 'center'
    },
    {
      prop: 'wating_pay',
      label: '待审',
      width: 75,
      align: 'center'
    },
    {
      prop: 'school',
      label: '学校',
      width: 220
    },
    {
      label: '报名信息',
      width: 130,
      align: 'center',
      slot: 'apply'
    },
    {
      label: '退定信息',
      width: 100,
      align: 'center',
      slot: 'cancel'
    },
    {
      label: '已联系',
      width: 106,
      align: 'center',
      slot: 'contact'
    },

    {
      label: '备注',
      width: 160,
      align: 'center',
      slot: 'remark'
    }
  ]);

  /** 表格选中数据 */
  const selections = ref([]);

  /** 当前编辑的信息 */
  const current = ref([]);

  /** 当前编辑的信息 */
  const currentId = ref(0);

  /** 当前工作的信息 */
  const job = ref([]);

  /** 当前工作的企业信息 */
  const company = ref([]);

  /** 是否显示编辑弹窗 */
  const showAdd = ref(false);

  /** 是否显示编辑弹窗 */
  const showPay = ref(false);

  /** 是否显示编辑弹窗 */
  const showPunish = ref(false);

  /** 是否显示编辑弹窗 */
  const showCancel = ref(false);

  /** 是否显示编辑弹窗 */
  const showNote = ref(false);

  /** 是否显示编辑弹窗 */
  const showSignIn = ref(false);

  /** 是否显示编辑弹窗 */
  const jobId = ref(0);

  const getId = () => {
    const { query } = unref(currentRoute);
    jobId.value = Number(query.id);
  };
  getId();
  /** 更新排序 */
  const updateSort = () => {
    console.log(tableRef.value.getData());
    var list = tableRef.value.getData();
    var requestData = [];
    for (var i = 0; i < list.length; i++) {
      const v = {
        id: list[i].id,
        sort: list[i].sort
      };
      requestData.push(v);
    }
    console.log(requestData);
    updateApplyRecoedSort({ datas: JSON.stringify(requestData) })
      .then(() => {
        EleMessage.success('更新成功!');
        reload();
      })
      .catch(() => {});
  };

  /** 表格数据源 */
  const datasource = ({ page, where, orders }) => {
    return pageApplyRecord({
      ...where,
      ...orders,
      page,
      limit: 99999999,
      id: jobId.value
    });
  };

  /** 导出表格 */
  const exportExcel = () => {
    const loading = EleMessage.loading('请求中..');
    tableRef.value?.fetch(({ where }) => {
      // 方法的参数与数据源的完全一致
      // 请求查询全部接口
      console.log(where);
      var requestData = where;
      requestData.id = jobId.value;
      requestData.limit = 99999999;
      requestData.page = 1;

      exportApplyRecordList(requestData)
        .then((res) => {
          loading.close();
          window.open(res);
        })
        .catch(() => {
          loading.close();
        });
    });
  };

  const statusText = (value) => {
    const cs = {
      1: '正常',
      0: '退定'
    };
    return cs[value];
  };
  const statusType = (state) => {
    const stateMap = {
      1: 'success',
      0: 'info'
    };
    return stateMap[state];
  };

  /** 设为录取 */
  const accept = (row = null) => {
    if (row !== null && row.accept === 1) return false;
    const rows = row == null ? selections.value : [row];

    if (!rows.length) {
      EleMessage.error('请至少选择一条数据');
      return;
    }
    ElMessageBox.confirm(
      '确定要将“' + rows.map((d) => d.realname).join(', ') + '”设为已录取吗?',
      '系统提示',
      { type: 'warning', draggable: true }
    )
      .then(() => {
        const loading = EleMessage.loading('请求中..');
        console.log(rows.map((d) => d.id));
        var selects = rows.map((d) => d.id);
        var ids = [];
        for (let i = 0; i < selects.length; i++) {
          const v = selects[i];
          ids.push(v);
        }
        ids = JSON.stringify(ids);
        setApplyRecordAccept({ ids })
          .then((msg) => {
            loading.close();
            EleMessage.success(msg);
            reload();
          })
          .catch((e) => {
            loading.close();
            EleMessage.error(e.message);
          });
      })
      .catch(() => {});
  };

  // 放鸽子
  const airplane = (row) => {
    // if (row.airplane === 1) this.airplaneCount++;
    // if (row.airplane === 0) this.airplaneCount--;
    row.airplane = row.airplane === 0 ? 1 : 0;
    updateAirplane({
      id: row.id,
      airplane: row.airplane,
      student_id: row.member_id
    })
      .then(() => {
        EleMessage.success('操作成功!');
      })
      .catch(() => {});
  };
  // 已联系
  const contact = (row) => {
    row.contact = row.contact === 0 ? 1 : 0;
    updateApplyRecordContact({ id: row.id, contact: row.contact })
      .then((res) => {
        EleMessage.success('操作成功!');
        row.contact_user = res.data.contact_user;
        row.contact_time = res.data.contact_time;
        row.contact = res.data.contact;
      })
      .catch(() => {});
  };

  /** 搜索 */
  const reload = (where) => {
    const { query } = unref(currentRoute);
    jobId.value = Number(query.id);
    getJob();
    selections.value = [];
    tableRef.value?.reload?.({ page: 1, where });
  };

  /** 处罚 */
  const openPunish = () => {
    showPunish.value = true;
  };

  /** 退定 */
  const openCancel = (row) => {
    current.value = row ?? null;
    showCancel.value = true;
  };

  /** 添加备注 */
  const addNote = (row) => {
    currentId.value = row.id;
    current.value = null;
    showNote.value = true;
  };

  /** 编辑备注 */
  const editNote = (row) => {
    current.value = row ?? null;
    showNote.value = true;
  };

  /** 添加报名记录 */
  const openAdd = () => {
    showAdd.value = true;
  };

  /** 签到表 */
  const openSignIn = () => {
    showSignIn.value = true;
  };

  /** 发工资 */
  const openPay = () => {
    showPay.value = true;
  };
  /** 获取当前工作的信息 */
  const getJob = () => {
    getJobById({ id: jobId.value })
      .then((res) => {
        console.log(res);
        job.value = res;
        company.value = res.company;
      })
      .catch((e) => {
        EleMessage.error(e.message);
      });
  };

  watch(
    currentRoute,
    (route) => {
      if (unref(route).path !== ROUTE_PATH) {
        return;
      }
      reload();
      searchRef.value?.reset();
    },
    { immediate: true }
  );
</script>

<script>
  export default {
    name: 'SystemUser'
  };
</script>
